package com.dht.xiao.jianye.base;

import android.app.Application;
import android.content.Context;
import android.content.Intent;
import android.os.Environment;
import android.text.TextUtils;

import com.dht.xiao.jianye.BuildConfig;
import com.dht.xiao.jianye.activity.MainActivity;
import com.dht.xiao.jianye.utils.DBManager;
import com.dht.xiao.jianye.utils.LogToFile;
import com.dht.xiao.jianye.utils.MyErrorTranslator;
import com.lzy.okgo.cookie.CookieJarImpl;
import com.lzy.okgo.cookie.store.SPCookieStore;
import com.squareup.leakcanary.LeakCanary;
import com.tencent.bugly.Bugly;
import com.tencent.bugly.crashreport.CrashReport;

import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;

import cn.dlc.commonlibrary.okgo.OkGoWrapper;
import cn.dlc.commonlibrary.okgo.exception.ApiException;
import cn.dlc.commonlibrary.okgo.logger.JsonRequestLogger;
import cn.dlc.commonlibrary.utils.PrefUtil;
import cn.dlc.commonlibrary.utils.ResUtil;
import cn.dlc.commonlibrary.utils.ScreenUtil;
import cn.dlc.commonlibrary.utils.SystemUtil;
import cn.wch.ch34xuartdriver.CH34xUARTDriver;
import okhttp3.OkHttpClient;

/**
 * Created by Administrator on 2018/8/28/028.
 */

public class App extends Application {
    public static CH34xUARTDriver driver;// 需要将CH34x的驱动类写在APP类下面，使得帮助类的生命周期与整个应用程序的生命周期是相同的
    @Override
    public void onCreate() {
        super.onCreate();
      //  Thread.setDefaultUncaughtExceptionHandler(restartHandler);
        if (SystemUtil.isMainProcess(this)) {
            ScreenUtil.init(this); // 获取屏幕尺寸
            ResUtil.init(this); // 资源
            PrefUtil.init(this); // SharedPreference
            // 网络
            OkHttpClient.Builder builder = new OkHttpClient.Builder();
            // builder.addInterceptor(new ChuckInterceptor(getApplicationContext()));
            builder.cookieJar(new CookieJarImpl(new SPCookieStore(this)));
            OkGoWrapper.initOkGo(this, builder.build());
            OkGoWrapper.instance()
                    // 错误信息再格式化
                    .setErrorTranslator(new MyErrorTranslator())
                    // 拦截网络错误，一般是登录过期啥的
                    .setErrorInterceptor(tr -> {
                        if (tr instanceof ApiException) {
                            ApiException ex = (ApiException) tr;
                            if (ex.getCode() == 101) {
                                return true;
                            }
                        }
                        return false;
                    })
                    // 打印网络访问日志的
                    .setRequestLogger(new JsonRequestLogger(BuildConfig.DEBUG, 30));
        }
        initBugly();
        LogToFile.init(Environment.getExternalStorageState());
//        SilentUpdateUtil.getInstance().setSilentUpdateListener(new SilentUpdateListener() {
//            @Override
//            public void onUpdateSuccess() {
//                Intent intent2 = new Intent(getApplicationContext(), MainActivity.class);
//                intent2.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
//                startActivity(intent2);
//            }
//
//            @Override
//            public void onUpdateFail() {
//
//            }
//        });
      //  LeakCanary.install(this);
        DBManager.getInstance(this).init();
    }

    private void initBugly() {
        Context context = getApplicationContext();
        // 获取当前包名
        String packageName = context.getPackageName();
        // 获取当前进程名
        String processName = getProcessName(android.os.Process.myPid());
        // 设置是否为上报进程
        CrashReport.UserStrategy strategy = new CrashReport.UserStrategy(context);
        strategy.setUploadProcess(processName == null || processName.equals(packageName));
        // 初始化Bugly
        //Bugly.init(getApplicationContext(), "5646465456", false, strategy);
    }

    private static String getProcessName(int pid) {
        BufferedReader reader = null;
        try {
            reader = new BufferedReader(new FileReader("/proc/" + pid + "/cmdline"));
            String processName = reader.readLine();
            if (!TextUtils.isEmpty(processName)) {
                processName = processName.trim();
            }
            return processName;
        } catch (Throwable throwable) {
            throwable.printStackTrace();
        } finally {
            try {
                if (reader != null) {
                    reader.close();
                }
            } catch (IOException exception) {
                exception.printStackTrace();
            }
        }
        return null;
    }

    // 创建服务用于捕获崩溃异常
    private Thread.UncaughtExceptionHandler restartHandler = new Thread.UncaughtExceptionHandler() {
        @Override
        public void uncaughtException(Thread thread, Throwable ex) {
            PrefUtil.getDefault().saveString("error", ex.getMessage());
            App.this.restartApp();//发生崩溃异常时,重启应用
        }
    };

    public void restartApp() {
//        Intent intent = new Intent(this, MainActivity.class);
//        intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK);
//        startActivity(intent);
//        android.os.Process.killProcess(android.os.Process.myPid());  //结束进程之前可以把你程序的注销或者退出代码放在这段代码之前

    }
//productionmanage

}
